package com.aclass.xqx.classscreen.utlis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import com.aclass.xqx.classscreen.adapter.BannerPaddingViewHolder;
import com.aclass.xqx.classscreen.db.CardStudent;
import com.aclass.xqx.classscreen.db.ReadNews;
import com.aclass.xqx.classscreen.db.StudentNews;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by xqx on 2017/11/14.
 */

public class AppUtlis {
    //当前透明度
    public static void backgroundAlpha(Context context, float bgAlpha) {
        WindowManager.LayoutParams lp = ((Activity) context).getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        ((Activity) context).getWindow().setAttributes(lp);
    }

    //未读消息按时间排序
    public static void ListSort(List<StudentNews> list) {
        Collections.sort(list, new Comparator<StudentNews>() {
            @Override
            public int compare(StudentNews o1, StudentNews o2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    Date dt1 = format.parse(o1.getNewsTime());
                    Date dt2 = format.parse(o2.getNewsTime());
                    if (dt1.getTime() > dt2.getTime()) {
                        return -1;
                    } else if (dt1.getTime() < dt2.getTime()) {
                        return 1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }

    //已读消息按时间排序
    public static void ListSort1(List<ReadNews> list) {
        Collections.sort(list, new Comparator<ReadNews>() {
            @Override
            public int compare(ReadNews o1, ReadNews o2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    Date dt1 = format.parse(o1.getNewsTime());
                    Date dt2 = format.parse(o2.getNewsTime());
                    if (dt1.getTime() > dt2.getTime()) {
                        return -1;
                    } else if (dt1.getTime() < dt2.getTime()) {
                        return 1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }

    //获取app版本
    public static String packageMas(Context context) throws PackageManager.NameNotFoundException {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
        return pi.versionName;
    }

    //获取app版本
    public static int packageCode(Context context) throws PackageManager.NameNotFoundException {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
        return pi.versionCode;
    }

    public static void setpa(MZBannerView mzBannerView, List<String> list) {

        mzBannerView.setPages(list, new MZHolderCreator<BannerPaddingViewHolder>() {
            @Override
            public BannerPaddingViewHolder createViewHolder() {
                return new BannerPaddingViewHolder();
            }
        });
    }

    public static float px2dp(Context context, float pxVal)

    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);

    }

    public static float px2sp(Context context, float pxVal)

    {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }

    public static int getInt(int i) {
        if (i % 72 == 0) {
            i = i / 72;
            return i;
        } else {
            i = i / 72;
            return (i + 1);
        }
    }

    public static List<String> handleText(String str, int counts, float nums) {
        List<String> strclass = new ArrayList<>();
        if (TextUtils.isEmpty(str)) {
            return strclass;
        }
        int count = 0;
        float num = 0;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char item = str.charAt(i);
            if (item < 128) {
                count = count + 1;
                num = num + 0.5f;
                if (count >= counts) {
                    builder.append(" " + item);
                    count = 0;
                } else {
                    builder.append(item);
                }
            } else {
                ++num;
                builder.append(item);
                count += 2;
            }
//            Log.e("WWW123", num + "  hao");
            if (num >= nums) {
                Log.e("WWW123", num + "  haojin");
                strclass.add(builder.toString());
                Log.e("WWW123", builder.toString() + "  内容");
                builder.setLength(0);
                num = 0;
            }
            if (i == str.length() - 1) {
                strclass.add(builder.toString());
                Log.e("Con", count + " zuih");
                builder.setLength(0);
            }
//            if (i==str.length()-1){
//                strclass.add(builder.toString());
//                Log.e("Con",count+" zuih");
////                builder.setLength(0);
//            }

        }


        return strclass;
    }

    public static String md5(String content) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("NoSuchAlgorithmException", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UnsupportedEncodingException", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * 32位MD5加密方法
     * 16位小写加密只需getMd5Value("xxx").substring(8, 24);即可
     *
     * @param sSecret
     * @return
     */
    public static String getMd5Value(String sSecret) {
        try {
            MessageDigest bmd5 = MessageDigest.getInstance("MD5");
            bmd5.update(sSecret.getBytes());
            int i;
            StringBuffer buf = new StringBuffer();
            byte[] b = bmd5.digest();// 加密
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
//            buf.substring(8, 24).toString().toUpperCase()
            return buf.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }



    /**
     * 删除之前的apk
     *
     * @param apkName apk名字
     * @return
     */
    public static File clearApk(String apkName) {
        File apkFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Class", apkName);
        if (apkFile.exists()) {
            apkFile.delete();
        }
        return apkFile;
    }

    //普通安装
    public static void installNormal(Context context, String apkPath) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            File file = (new File(apkPath));
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, "com.aclass.xqx.classscreen", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(new File(apkPath)),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    public static boolean isEthernetDeviceUp(String ifname) {
        try {
            boolean retval = false;
            FileReader fr = new FileReader("/sys/class/net/" + ifname + "/operstate");
            BufferedReader br = new BufferedReader(fr, 32);
            String status = br.readLine();

            if (status != null && status.equals("up")) {
//                Slog.d(TAG, ifname + " status:" + status);
                retval = true;
            } else if (status != null && status.equals("down")) {
//                Slog.d(TAG, ifname + " status:" + status);
                retval = false;
            } else {
                retval = false;
            }

/****************************Add Start****************************/

            FileReader kFr = new FileReader("/sys/class/net/" + ifname + "/carrier");
            BufferedReader kBr = new BufferedReader(kFr, 32);
            String kStatus = kBr.readLine();
            if (kStatus != null && kStatus.equals("1")) {
//                Slog.d(TAG, DevName[0] + " kStatus:" + kStatus);
                retval = true;
            } else if (kStatus != null && kStatus.equals("0")) {
//                Slog.d(TAG, DevName[0] + " kStatus:" + kStatus);
                retval = false;
            } else {
                retval = false;
            }

            kBr.close();
            kFr.close();

/****************************Add End****************************/

            br.close();
            fr.close();
            return retval;
        } catch (IOException e) {
//            Slog.d(TAG, "get " + ifname + " status error");
            return false;
        }
    }

    public static void up() throws IOException {
      Runtime proc = Runtime.getRuntime();
      proc.exec(new String[]{"su", "-c", "netcfg eth0 up"});
    }
    public static void down() throws IOException {
      Runtime proc = Runtime.getRuntime();
      proc.exec(new String[]{"su", "-c", "netcfg eth0 down"});
    }
    /**
     * 获取有线地址
     *
     * @return
     */
    public static String getEtherNetIP() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {}
        return "0.0.0.0";
    }
}













































































































































































